# -*- coding: utf-8 -*-
import hashlib, hmac, json, os, sys, time
from datetime import datetime
import requests


# 密钥参数
# 需要设置环境变量 TENCENTCLOUD_SECRET_ID，值为示例的 AKIDz8krbsJ5yKBZQpn74WFkmLPx3*******
secret_id = 'AKIDvkMsDPeeQzJPGtKXWFjNnz64qRpzVqwo'
# 需要设置环境变量 TENCENTCLOUD_SECRET_KEY，值为示例的 Gu5t9xGARNpq86cd98joQYCN3*******
secret_key = 'iCRRbYIqBJF2e4JOJ4cy72iASZTBh05v'
service = "monitor"
host = "monitor.tencentcloudapi.com"
endpoint = "https://" + host
region = "ap-beijing"
action = "GetMonitorData"
version = "2018-07-24"
algorithm = "TC3-HMAC-SHA256"
timestamp = int(time.time())
# timestamp = 1694505777
date = datetime.utcfromtimestamp(timestamp).strftime("%Y-%m-%d")
def monitorMain(MetricName,MetricTitle) :

    params = {"Namespace":"QCE/REDIS_MEM","MetricName":MetricName,"Period":300,"Instances":[{"Dimensions":[{"Name":"instanceid","Value":"crs-cgozkoox"}]}]}
    #params = {}
    authorization = getAuthorization(params)
    last_timestamp,last_value = getRedisMonitorData(params,authorization)
    uploadOpenFalcon(MetricTitle,last_timestamp,last_value)

#计算签名
def getAuthorization(params):
    # ************* 步骤 1：拼接规范请求串 *************
    http_request_method = "POST"
    canonical_uri = "/"
    canonical_querystring = ""
    ct = "application/json; charset=utf-8"
    payload = json.dumps(params)
    canonical_headers = "content-type:%s\nhost:%s\nx-tc-action:%s\n" % (ct, host, action.lower())
    signed_headers = "content-type;host;x-tc-action"
    hashed_request_payload = hashlib.sha256(payload.encode("utf-8")).hexdigest()
    canonical_request = (http_request_method + "\n" +
                         canonical_uri + "\n" +
                         canonical_querystring + "\n" +
                         canonical_headers + "\n" +
                         signed_headers + "\n" +
                         hashed_request_payload)
    #print(canonical_request)

    # ************* 步骤 2：拼接待签名字符串 *************
    credential_scope = date + "/" + service + "/" + "tc3_request"
    hashed_canonical_request = hashlib.sha256(canonical_request.encode("utf-8")).hexdigest()
    string_to_sign = (algorithm + "\n" +
                      str(timestamp) + "\n" +
                      credential_scope + "\n" +
                      hashed_canonical_request)
    #print(string_to_sign)
    # ************* 步骤 3：计算签名 *************

    secret_date = sign(("TC3" + secret_key).encode("utf-8"), date)
    secret_service = sign(secret_date, service)
    secret_signing = sign(secret_service, "tc3_request")
    signature = hmac.new(secret_signing, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
    #print(signature)
    # ************* 步骤 4：拼接 Authorization *************
    authorization = (algorithm + " " +
                     "Credential=" + secret_id + "/" + credential_scope + ", " +
                     "SignedHeaders=" + signed_headers + ", " +
                     "Signature=" + signature)


    # print(authorization)
    '''
        print('linux  curl -X POST ' + endpoint
          + ' -H "Authorization: ' + authorization + '"'
          + ' -H "Content-Type: application/json; charset=utf-8"'
          + ' -H "Host: ' + host + '"'
          + ' -H "X-TC-Action: ' + action + '"'
          + ' -H "X-TC-Timestamp: ' + str(timestamp) + '"'
          + ' -H "X-TC-Version: ' + version + '"'
          + ' -H "X-TC-Region: ' + region + '"'
          + " -d '" + payload + "'")
    '''
    return authorization

# 计算签名摘要函数
def sign(key, msg):
    return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()


def getRedisMonitorData(params,authorization):
    url = endpoint
    headers = {
        'Authorization': authorization,
        'Content-Type': 'application/json; charset=utf-8',
        'Host': host,
        'X-TC-Action': action,
        'X-TC-Timestamp': str(timestamp),
        'X-TC-Version': version,
        'X-TC-Region': region
    }
    payload = json.dumps(params)
    data = payload

    r = requests.post(url, headers=headers, data=data)
    print(r.text)

    json_data = json.loads(r.text)
    timestamps = json_data['Response']['DataPoints'][0]['Timestamps']
    values = json_data['Response']['DataPoints'][0]['Values']
    last_timestamp = timestamps[-1]
    last_value = values[-1]
    last_value = int(last_value)

    print('Last Timestamp:', last_timestamp)
    print('Last Value:', last_value)
    return last_timestamp,last_value

def uploadOpenFalcon(Metric,last_timestamp,last_value):

    url = 'http://127.0.0.1:1988/v1/push'
    headers = {
        'Content-Type': 'application/json'
    }
    payload = [
        {
            'Metric': Metric,
            'Endpoint': 'tx-device-oneid-redis-cluster-01-67-136',
            'CounterType': 'GAUGE',
            'Step': 60,
            'TAGS': 'port=7701',
            'Timestamp': last_timestamp,
            'Value': last_value
        }
    ]
    data = json.dumps(payload)

    r = requests.post(url, headers=headers, data=data)
    print(r.text)


if __name__ == '__main__':
    monitorMain("Memused","redis.QPS")